package com.siteseat.crudeq.broker.deploy;

import java.io.File;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.siteseat.common.deploy.AbstractDeployRepository;
import com.siteseat.common.deploy.DeployEntry;
import com.siteseat.common.exception.InternalException;
import com.siteseat.common.foundation.PropertyHelper;
import com.siteseat.common.security.Credential;
import com.siteseat.common.security.Permission;
import com.siteseat.common.security.SecurityException;
import com.siteseat.common.security.SecurityManager;

/**
 *
 * @author yqiang
 */
public class UserDeployRepository extends AbstractDeployRepository {
  
  private Class<Credential> credentialClass;

  /**
   * Gets the credentialClass
   *
   * @return the credentialClass
   */
  public Class<Credential> getCredentialClass() {
    return credentialClass;
  }

  /**
   * Sets the credentialClass
   *
   * @param credentialClass the credentialClass to set
   */
  public void setCredentialClass( Class<Credential> credentialClass ) {
    this.credentialClass = credentialClass;
  }

  /**
   * 
   *
   * @param file
   * @return
   */
  public Credential loadUser( File f ) {
    return parseEntityFromJsonFile( f, credentialClass );
  }
  
  /**
   * 
   *
   * @param user
   */
  public void validateUser( Credential user ) {
    if( StringUtils.isBlank( user.getName() ) ) {
      throw new InternalException( "user name cannot be blank" );
    }
    if( StringUtils.isBlank( user.getPassword() ) ) {
      throw new InternalException( "password cannot be blank" );
    }
  }
  
  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDeploy(DeployEntry entry) throws SecurityException {
    File f = entry.getFile();
    Credential u = loadUser( f );
    validateUser( u );
    entry.setData( u );
    
    SecurityManager sm = getSecurityManager();
    String a = getActorName();
    String n = u.getName();
    
    sm.addCredential( a, u );
    
    for( Map.Entry<String,Set<Permission>> ent: u.getPermissions().entrySet() ) {
      sm.grant( a, n, ent.getKey(), ent.getValue() );
    }
  }


  /**
   * {@inheritDoc}
   */
  @Override
  protected void doUndeploy(DeployEntry entry) throws SecurityException {
    Credential u = (Credential)entry.getData();
    SecurityManager sm = getSecurityManager();
    String a = getActorName();
    String n = u.getName();
    
    getSecurityManager().removeCredential( a, n, u.getPassword() );
    
    for( Map.Entry<String,Set<Permission>> ent: u.getPermissions().entrySet() ) {
      sm.revoke( a, n, ent.getKey(), ent.getValue() );
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doInit() throws Exception {
    super.doInit();
    PropertyHelper.ensureNotNull( log, getCredentialClass(), "credentialClass" );    
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected void doDestroy() throws Exception {
    // do nothing so far
  }
  
}
